﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;
using System.Collections;

namespace Pixcom
{    
   

    public partial class Pixcom_Form : Form
    {
        
 
        
        //// 写入INI文件       
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filepath);
        /// 读取INI文件        
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retval, int size, string filePath);

        private string IniFilePath = Application.StartupPath + "\\Config.ini";//获取INI文件路径    

       private AsynchronousSocketListener asyncServer { get; set; }   
   
        public ImageObject imgobj { get; set; }

        private static string ReadString(string section, string key, string def, string filePath)
        {
            StringBuilder temp = new StringBuilder(128);
            try
            {
                GetPrivateProfileString(section, key, def, temp, 128, filePath);
            }
            catch
            { }
            return temp.ToString();
        }

        /************************************************
        *       exe初始化
        * **********************************************/
        public Pixcom_Form(AsynchronousSocketListener asyncS=null,ImageObject imgobj=null)
        {
            InitializeComponent();

          
            asyncServer=asyncS;
            //是否有TCP监听服务，如果有就是TCP，没有就是UART
            if (asyncServer == null)
            {
                rbtnTCP.Checked = false;
                rbtnTCP.Enabled = false;
                rbtnUART.Checked = true;
                rbtnUART.Enabled = true;
                gBoxUart.Enabled = true;
                gBoxUart.Visible = true;
            }
            else {
                rbtnTCP.Checked = true;
                rbtnTCP.Enabled = true;
                rbtnUART.Enabled = false;
                rbtnUART.Checked = false;
                gBoxUart.Enabled = false;
                gBoxUart.Visible = false;
            }

            if (imgobj != null)
            {
                this.imgobj =  imgobj;
            } 
            //asyncTCP = new AsynchronousSocketListener(SafeupdateUI);
            /***
            ArrayList 种存的是指针  取出来的元素修改了也是修改的 ArrayList中的元素
            */
          //  SocketObject OBJ = new SocketObject(null, SOCKET_STAT.Unknow);
            //ArrayList alist = new ArrayList();
            //alist.Add( OBJ);
            //SocketObject tobj =(SocketObject) alist[0];
            //tobj.errStr = "cuowude zifuc";

            //MessageBox.Show("ddd" + ((SocketObject)alist[0]).errStr);



            //Hashtable table = new Hashtable();
            //table.Add("1", OBJ);

            //SocketObject tobj = table["1"] as SocketObject;
            //tobj.errStr = "noew";
            //SocketObject tobj1 = table["1"] as SocketObject;
            //MessageBox.Show("ddd" + tobj1.errStr);
             


        }
        private void writeToFile(String text) {




            FileStream fs = new FileStream("e:/tttttt.txt", FileMode.OpenOrCreate| FileMode.Append);
            StreamWriter sw = new StreamWriter(fs);
            //开始写入
          //  sw.Write(text);
            sw.WriteLine(text);
            //清空缓冲区
            sw.Flush();
            //关闭流
            sw.Close();
            fs.Close();
        }
        public void updateSocket(ImageObject imgobj) {

            this.imgobj = imgobj;
            comboID.Text = imgobj.eqpid.ToString();
            if (imgobj.OnLine == true)
            {
                lbTCPstatus.BackColor = Color.Green;
                lbTCPstatus.Text = "已链接";
            }
            else
            {
                lbTCPstatus.BackColor = Color.Red;
                lbTCPstatus.Text = "未链接";
            }
 
             
        }

         public void SafeupdateUI(object state)
        {
            


            byte[] tempbuf = new byte[PicProtocal.SP_INBUFFER_MAX_SIZE];
            ImageObject obj = (ImageObject)state;
 
             
                //拍图过程中动态加载半成品到界面
                if (imgobj.isPictureing()) {

               
                    FileStream fs = new FileStream(imgobj.path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                    System.IO.StreamReader file = new System.IO.StreamReader(fs);
                    //    string sTxt = file.ReadLine();
                    //    file.Close();
 
                    pbMain.Image = Image.FromStream(fs);
                    file.Close();
               
                }
                if (imgobj.ImageOK==true) {
                    imgobj.ImageOK =false;
                    gpBoxShow.Enabled = true;
                    pbMain.Image = Image.FromFile(imgobj.path);
 
                }
            
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if(File.Exists(IniFilePath))    //已经存在INI文件，读取值
            {
                string port = ReadString("Setting", "PORT", "", IniFilePath);
                string id =   ReadString("Setting", "ID", "", IniFilePath);
                string baudrate = ReadString("Setting", "BAUDRATE", "", IniFilePath);
                comboPort.Text = port;
                comboID.Text = id;
                comboBaudrate.Text = baudrate;
            }
            else   //不存在INI文件，新建一个
            {
                WritePrivateProfileString("Setting", "PORT", "COM1", IniFilePath);
                WritePrivateProfileString("Setting", "ID", "0", IniFilePath);
                WritePrivateProfileString("Setting", "BAUDRATE", "115200", IniFilePath);
                comboPort.Text = "COM1";
                comboID.Text = "0";
                comboBaudrate.Text = "115200";
            }            
            comboMultiInterval.Text = "0.1";
            comboMultiTotal.Text = "5";
            comboFixExpo.Text = "0";
            //开启TCPsocket 监听服务 
          //  asyncTCP.StartListening();
        }

        /************************************************
        *       计时器事件，提取串口接收数据
        * **********************************************/
        private void tmrSP_Tick(Object source, EventArgs e)    //每50ms调用一次
        {
            int rcvseglen = 0, saylen;
            if (RS_port.IsOpen)
            {
                /*串口新一轮接收正在等待第一批数据*/
                if (imgobj. stSP.RcvBgn == false)
                {
                    if (RS_port.BytesToRead > 0)  //串口收到第一批数据
                    {
                        imgobj.stSP.RcvBgn = true;
                        imgobj.stSP.RcvMark = RS_port.BytesToRead;
                        imgobj.stSP.RcvCnt = 0;
                        imgobj.stSP.Timeup = 0;                   
                    }
                }
                /*串口已经处于接收流程*/
                else
                {
                    if(RS_port.BytesToRead == imgobj.stSP.RcvMark)   //没有新的数据被接收
                    {
                        tmrSP.Stop();
                        rcvseglen = RS_port.BytesToRead;       //记录本段串口接收的长度 
                        if (rcvseglen > 0)
                        {
                            imgobj.stSP.Timeup = 0;    //串口接收到数据的话，则清零超时计数器
                            if ((rcvseglen + imgobj.stSP.RcvCnt) < PicProtocal.SP_INBUFFER_MAX_SIZE)  //判断总接收长度是否有效
                            {
                                RS_port.Read(imgobj.stSP.RS_RcvBuf, imgobj.stSP.RcvCnt, rcvseglen);       //从串口copy本段接收的数据                                                 
                                imgobj.stSP.RcvMark = RS_port.BytesToRead;

                                imgobj.stSP.RcvCnt += rcvseglen;     //更新本次接收后的总长
                                if (imgobj.stSP.RS_RcvBuf[(imgobj.stSP.RcvCnt - 1)] == 0xE7)      //检测最新收到的数据看看是否跟包尾标志一致
                                {
                                    saylen = imgobj.stSP.RS_RcvBuf[1] * 256 + imgobj.stSP.RS_RcvBuf[2];     //获得包中声明长度
                                    if (imgobj.stSP.RcvCnt == (saylen + 5))    //声明长度+5跟已接收实际长度一致，才去处理接收包
                                    {
                                       // PicProtocal.RS_RcvHandler(imgobj);
                                        imgobj.stSP.RcvBgn = false;       //重新开始接收新的包
                                    }
                                    else    //还未接收完数据，或是实际接收大于声明长度，则等待超时丢弃
                                    {; }
                                }
                                else        //本次接收的最后一个数据不是包尾标志
                                {; }
                            }
                            else    //超长无效，丢弃本包，重新开始新包接收
                            {
                                imgobj.stSP.RcvBgn = false;                                
                            }
                        }
                        else    //串口没有收到数据，超时+1
                        {
                            imgobj.stSP.Timeup++;
                            if (imgobj.stSP.Timeup > 5)       //超时无收到数据，且之前收到的数据长度不是一个完整包。有可能是噪音或丢失包尾。丢弃，重新收包
                            {
                                imgobj.stSP.RcvBgn = false;
                            }
                            else{; }
                        }
                        tmrSP.Start();      //继续跑定时器
                    }
                    else        //接收到新数据，刷新接收标记
                    {
                        if (RS_port.BytesToRead < PicProtocal.SP_INBUFFER_MAX_SIZE)
                        {
                            imgobj.stSP.RcvMark = RS_port.BytesToRead;
                        }
                        else    //长度出现异常了
                        {
                            tmrSP.Stop();
                            RS_port.Close();
                            MessageBox.Show("串口接收数据超长导致死机，自动退出", "发生异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            Application.Exit();
                        }
                    }
                }
            }
            else if(imgobj.stSP.Open == true)
            {
                imgobj.stSP.Open = false;
                MessageBox.Show("串口被断开，请检查并重新打开", "发生异常", MessageBoxButtons.OK, MessageBoxIcon.Error);                                
                btnOpen.Text = "打开串口";
                btnOpen.BackColor = Color.Chartreuse;
                comboPort.Enabled = true;
                comboBaudrate.Enabled = true;
                comboID.Enabled = true;
                RS_port.Close();
            }          
        }


        /************************************************
        *       按键事件，终止传图数据
        * **********************************************/
        private void btnStop_Click(object sender, EventArgs e)
        {
            imgobj.stSP.ForceStop = true;
            btnStart.Enabled = true;
            GP_ShotSetting.Enabled = true;
        }

        /************************************************
        *       按键事件，打开关闭串口
        * **********************************************/
        private void btnOpen_Click(object sender, EventArgs e)
        {
            if (imgobj.stSP.Open == false)
            {               
                try
                {
                    RS_port.PortName = comboPort.Text;
                    RS_port.BaudRate = int.Parse(comboBaudrate.Text);
                    WritePrivateProfileString("Setting", "PORT", RS_port.PortName, IniFilePath);
                    WritePrivateProfileString("Setting", "ID", comboID.Text, IniFilePath);
                    WritePrivateProfileString("Setting", "BAUDRATE", comboBaudrate.Text, IniFilePath);
                    if (RS_port.BaudRate <= 115200)
                    {
                        tmrSP.Interval = 30;
                    }
                    else
                    {
                        tmrSP.Interval = 15;
                    }
                    RS_port.Open();
                    btnOpen.Text = "关闭串口";
                    btnOpen.BackColor = Color.Tomato;
                    comboPort.Enabled = false;
                    comboBaudrate.Enabled = false;
                    comboID.Enabled = false;
                    imgobj.stSP.Open = true;
                    btnStart.Enabled = true;
                    GP_ShotSetting.Enabled = true;
                    imgobj.stOVT.TotReSend = 0;
                    lblOVTRepe.Text = imgobj.stOVT.TotReSend.ToString();
                    lblState.Text = "指令状态";
                    tmrSP.Start();
                }
                catch(Exception ex)
                {
                    if(ex.GetType()==typeof(UnauthorizedAccessException))
                        MessageBox.Show(ex.Message+"\r\n串口已被占用", "发生异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    else if (ex.GetType() == typeof(InvalidOperationException))
                        MessageBox.Show(ex.Message + "\r\n串口已打开", "发生异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    else
                        MessageBox.Show(ex.Message+"\r\n找不到串口", "发生异常", MessageBoxButtons.OK,MessageBoxIcon.Error);
                }   
            }
            else
            {
                RS_port.Close();
                btnOpen.Text = "打开串口";
                btnOpen.BackColor = Color.Chartreuse;
                comboPort.Enabled = true;
                comboBaudrate.Enabled = true;
                comboID.Enabled = true;
                imgobj.stSP.Open = false;
            }
        }

        /************************************************
        *       按键事件，发出拍摄指令
        * **********************************************/
        private void btnStart_Click(object sender, EventArgs e)
        {
            byte cmd;
            int ovt = 1000;
            byte[] para = new byte[6];
            
            imgobj.stSP.ForceStop = false;            
            //选择图像分辨率
            if (rb7w.Checked == true)
            {
                para[0] = 0x01;
            }
            else if(rb30w.Checked==true)
            {
                para[0] = 0x02;
            }
            else if (rb50w.Checked == true)
            {
                para[0] = 0x03;
            }
            else if (rb80w.Checked == true)
            {
                para[0] = 0x04;
            }
            else if (rb120w.Checked == true)
            {
                para[0] = 0x05;
            }
            else if (rb200w.Checked == true)
            {
                para[0] = 0x06;
            }
            else if (rb310w.Checked == true)
            {
                para[0] = 0x07;
            }
            else if (rb500w.Checked == true)
            {
                para[0] = 0x08;
            }

                //选择图像质量
            if (rbQX.Checked == true)
            {
                para[1] = 0x01;
            }
            else if (rbQH.Checked == true)
            {
                para[1] = 0x02;
            }
            else if (rbQM.Checked == true)
            {
                para[1] = 0x03;
            }
            else if (rbQL.Checked == true)
            {
                para[1] = 0x04;
            }
            //选择图像色彩 
            if (rbBW.Checked == true)
            {
                para[1] |= 0x10;
            }
            else
            {
                para[1] &= 0x0F;
            }               

            if(rbMultiShot.Checked == true)     //多拍的设置
            {
                cmd = PicProtocal.RSCMD_MULTI_SHOT;
                switch (comboMultiInterval.Text)
                {
                    case "0.1": para[2] = 1; ovt = 100; break;
                    case "0.2": para[2] = 2; ovt = 200; break;
                    case "0.5": para[2] = 3; ovt = 500; break;
                    case "1.0": para[2] = 4; ovt = 1000; break;                    
                    default:para[2] = 1; ovt = 100; break;
                }
                switch (comboMultiTotal.Text)
                {
                    case "5":  para[2] |= 0x10; ovt *= 5; break;
                    case "10": para[2] |= 0x20; ovt *= 10; break;
                    case "15": para[2] |= 0x30; ovt *= 15; break;
                    case "20": para[2] |= 0x40; ovt *= 20; break;
                    default:   para[2] |= 0x10; ovt *= 5; break;
                }
                    //自动曝光
                if (rdoAutoExpo.Checked == true)        
                {
                    para[3] = 0;
                }
                else        //固定曝光
                {
                    para[3] = (byte)(0x80 | Byte.Parse(comboFixExpo.Text));
                }
                para[4] = para[5] = 0;
            }
            else    //单拍的设置                
            {
                cmd = PicProtocal.RSCMD_SINGLE_SHOT;
                para[2] = 1;        //jpg
                ovt = 500;
                //自动曝光
                if (rdoAutoExpo.Checked == true)
                {
                    para[3] = 0x00; 
                }
                else        //固定曝光
                {
                    para[3] = (byte)(0x80 | Byte.Parse(comboFixExpo.Text));
                }
                para[4] = para[5] = 0;                
            }
                        
            if (rbConstShot.Checked == true) 
            {
                Array.Copy(para, imgobj.stSP.ConstShotCMD, 6);        
            }
            imgobj.stOVT.TotReSend = 0;
            lblOVTRepe.Text = imgobj.stOVT.TotReSend.ToString();
            imgobj.stSP.RcvCnt = 0;
            gpBoxShow.Enabled = false;
           // btnStart.Enabled = false;
            GP_ShotSetting.Enabled = false;

            WriteData(PicProtocal.RS_PacketTx(imgobj.eqpid, cmd, 6, para));
            imgobj.stImg.Pktsz = 1;

            lblState.Text = "发出拍摄指令";
            Logger.Info("发送抓拍指令");     
        }

        /************************************************
        *       按键事件，手动保存图片处理
        * **********************************************/
        private void btnSavePic_Click(object sender, EventArgs e)
        {
            string tsm = System.DateTime.Now.ToString();
            tsm = tsm.Replace("/", "");
            tsm = tsm.Replace(":", "");
            tsm = tsm.Replace(" ", "-");
            SavePicDlg.FileName = "IMG-" + tsm;
            if (SavePicDlg.ShowDialog() == DialogResult.OK)
            {
                pbMain.Image.Save(SavePicDlg.FileName);
            }

        }

        /************************************************
       *       按键事件，设置自动保存路径
       * **********************************************/
        private void btnSavePath_Click(object sender, EventArgs e)
        {
            if (AutosaveFolderDlg.ShowDialog() == DialogResult.OK)
            {
                tbSavePath.Text = AutosaveFolderDlg.SelectedPath;
            }
        }

        /************************************************
        *       选择按键器事件，选择拍摄类型
        * **********************************************/
        private void rbShotType_CheckedChanged(object sender, EventArgs e)
        {
            if(rbMultiShot.Checked == true)
            {
                gBMultiset.Enabled = true;
                rb120w.Enabled = false;
                rb200w.Enabled = false;
                rb310w.Enabled = false;
                rb500w.Enabled = false;                                
                if ((rb7w.Checked == true) || (rb30w.Checked == true) || (rb50w.Checked == true) || (rb80w.Checked == true)) {; }
                else
                {
                    MessageBox.Show("快拍模式只能选择低四种分辨率\r请重选分辨率", "重选参数", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    rb30w.Checked = true;
                }
            }
            else
            {                
                gBMultiset.Enabled = false;
                rb120w.Enabled = true;
                rb200w.Enabled = true;
                rb310w.Enabled = true;
                rb500w.Enabled = true;                
            }
        }

     
 

        //发送数据到设备，根据当前选中的工作模式选择
        public   void WriteData(byte[] buf)
        {

            if (rbtnTCP.Checked == true)
            {
                asyncServer.Send(imgobj.eqpid, buf, 0, buf.Length);
            }
            else
            {
                RS_port.Write(buf, 0, buf.Length);
            }

        }

        /************************************************
         *       计时器事件，指令超时无应答处理
         * **********************************************/
        private void tmrCmdOVT_Tick(object sender, EventArgs e)
        {
            tmrCmdOVT.Stop();
            imgobj.stOVT.Timer++;      //累加时间
            if(imgobj.stOVT.Timer > imgobj.stOVT.Threshold)  //计时器值已超过预设时间阀值
            {
                imgobj.stOVT.Timer = 0;    //清零累加时间
                imgobj.stOVT.ReSendCnt++;      //次数+1
                imgobj.stOVT.TotReSend++;      //总次数累加
                lblOVTRepe.Text = imgobj.stOVT.TotReSend.ToString();
                if (imgobj.stOVT.ReSendCnt > PicProtocal.OVT_REPEAT_LIMIT)  //已经累加3次超时重发不响应
                {
                    lblState.Text = PicProtocal.OVT_REPEAT_LIMIT.ToString() + "次超时重发不响应，终止当前命令，排查故障";
                    btnStart.Enabled = true;
                    GP_ShotSetting.Enabled = true;
                }
                else                //尝试重发指令
                {
                    try
                    { //串口发送   
                      // RS_port.Write(imgobj.stSP.SndBuf, 0, 13);
                        WriteData(imgobj.stSP.SndBuf);

                        tmrCmdOVT.Start();
                        string stx = PicProtocal.byteToHexStr(imgobj.stSP.SndBuf, 0, 13);
                        stx = stx.Replace("-", " ");
                        stx += " (" + DateTime.Now.ToString("HH:mm:ss:fff") + ")\n";
                        rchTX.AppendText(stx);
                        rchTX.ScrollToCaret();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message + "\r\n串口被拔出", "出错了", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            else   //计时未到阀值，继续跑时钟
            {
                tmrCmdOVT.Start();
            }
        }


        /************************************************
        *       按键事件，发出自动对焦指令
        * **********************************************/
        private void btnFocusAuto_Click(object sender, EventArgs e)
        {
            lblFocusState.Text = "发出指令";
            WriteData(PicProtocal.RS_PacketTx(imgobj.eqpid, PicProtocal.RSCMD_FOCUS, 1, 0x01));            
        }

        /************************************************
        *       按键事件，发出读取焦距指令
        * **********************************************/
        private void btnFocusRead_Click(object sender, EventArgs e)
        {
            lblFocusState.Text = "发出指令";
            WriteData(PicProtocal.RS_PacketTx(imgobj.eqpid, PicProtocal.RSCMD_FOCUS, 1, 0x02));            
        }

        /************************************************
        *       按键事件，发出设置焦距指令
        * **********************************************/
        private void btnFocusSet_Click(object sender, EventArgs e)
        {
            int vcm = 0;
            try
            {
                vcm = int.Parse(tbFocusInput.Text);
            }
            catch (Exception  )
            {
                MessageBox.Show("设置焦距值范围：0—750", "NOTE", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            if (vcm <= 750)
            {
                lblFocusState.Text = "发出指令";
               WriteData( PicProtocal.RS_PacketTx(imgobj.eqpid, PicProtocal.RSCMD_FOCUS, 3, 0x03, (byte)(vcm >> 8), (byte)(vcm)));
            }
            else
            {
                MessageBox.Show("设置焦距值范围：0—750", "NOTE", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        /************************************************
        *       按键事件，发出查询参数指令
        * **********************************************/
        private void btnParaAsk_Click(object sender, EventArgs e)
        {
            WriteData( PicProtocal.RS_PacketTx(imgobj.eqpid, PicProtocal.RSCMD_ASK_PARA, 0));
        }


        /************************************************
        *       按键事件，发出设置参数指令
        * **********************************************/
        private void btnParaSet_Click(object sender, EventArgs e)
        {
            byte baud = 0, id = 0, pktsz = 0;            

            try
            {
                id = byte.Parse(comboSetID.Text);          //ID         
                switch (int.Parse(comboSetBaud.Text))       //baudrate
                {
                    case 9600: baud = 1; break;
                    case 19200: baud = 2; break;
                    case 38400: baud = 3; break;
                    case 57600: baud = 4; break;
                    case 115200: baud = 5; break;
                    case 230400: baud = 6; break;
                    case 460800: baud = 7; break;
                    case 921600: baud = 8; break;
                }
                switch (int.Parse(comboSetPKTsz.Text))  //包容量
                {
                    case 256: pktsz = 1; break;
                    case 512: pktsz = 2; break;
                    case 1024: pktsz = 3; break;
                    case 2048: pktsz = 4; break;
                }
                if (MessageBox.Show("确定对参数进行修改？\n修改完波特率或ID的话，记得先关闭串口，选择正确波特率和ID，重新打开串口才能正常使用", 
                                     "注意！！！", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    WriteData(PicProtocal.RS_PacketTx(imgobj.eqpid, PicProtocal. RSCMD_SET_PARA, 3, baud, id, pktsz));
                }
            }
            catch (Exception  )
            {                
                MessageBox.Show("请先从下拉框选择正确值", "NOTE", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            
        }

        /************************************************
        *      打钩框事件，检查自动保存路径是否已设置
        * **********************************************/
        private void chkAutoSave_CheckedChanged(object sender, EventArgs e)
        {
            if (chkAutoSave.Checked == true)
            {
                if (tbSavePath.Text == "")
                {
                    MessageBox.Show("请先选择自动保存路径", "NOTE", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    chkAutoSave.Checked = false;
                }
            }
        }

        private void btnOpenHelp_Click(object sender, EventArgs e)
        {
            MessageBox.Show("1、模块出厂默认波特率=115200，ID=0\n" +
                            "2、对于RS232，建议最高波特率不超460800\n" +
                            "3、对于RS485，50米内传输距离可用最高921600\n"+
                            "4、对于TTL无速度限制，传输距离最好在20cm内\n"+
                            "5、ID设为FF则为广播，所有终端都响应",
                "NOTE", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void btnFocusHelp_Click(object sender, EventArgs e)
        {
            MessageBox.Show("1、自动对焦耗时 750ms，手动对焦 10ms\n" +
                            "2、自动/手动对焦后，软件界面均会刷新显示最新镜头焦距\n" +
                            "3、镜头焦距数值与景物距离成反比，即焦距值越大拍的景越近\n" +
                            "4、每次自动/手动对焦后，拍摄模块会一直沿用最新的镜头焦距\n" +
                            "5、每次自动/手动对焦更新后的镜头焦距，拍摄模块自动掉电保存，并且重启后也会自动沿用最近更新的镜头焦距",
                "NOTE", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void btnShotHelp_Click(object sender, EventArgs e)
        {
            MessageBox.Show("1、单张拍指：1条指令 >> 拍1帧 >> 取1帧 >> 自动保存（可选）\n" +
                            "2、循环拍指：单张拍的形式无限循环\n" +
                            "3、快连拍指：1条指令 >> 拍N帧 >> 取第1帧 >> 自动保存（可选）......取第N帧 >> 自动保存（可选）\n"+
                            "4、同一固定曝光级数下，单张拍与快连拍的曝光效果会有所不同\n",
                            "NOTE", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        

        private void btnSysHelp_Click(object sender, EventArgs e)
        {
            MessageBox.Show("1、波特率、ID、包容量任意一个修改，均立刻生效，且掉电保存\n" +                            
                            "2、恢复出厂设置默认值：波特率=115200，ID=0，包容量=512\n",                           
                            "NOTE", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        /************************************************
    *       设置超时无应答倒计时函数
    * **********************************************/
        public   void ResetOVT_and_Start(int ovtms)
        {
            imgobj.stOVT.Threshold = ovtms * 10 / tmrCmdOVT.Interval;
            if (imgobj.stOVT.Threshold < 5) { imgobj.stOVT.Threshold = 5; }
            imgobj.stOVT.Timer = 0;
            imgobj.stOVT.ReSendCnt = 0;
            tmrCmdOVT.Start();
        }


        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("https://item.taobao.com/item.htm?spm=a1z10.1-c.w4004-12390016648.4.TPIZsS&id=543903585209");
        }


        /************************************************
       *       按键事件，发出复位指令
       * **********************************************/
        private void btnSysReset_Click(object sender, EventArgs e)
        {
            if(MessageBox.Show("确定进行复位?\n", "NOTE", MessageBoxButtons.OKCancel, MessageBoxIcon.Question)==DialogResult.OK)
            {
               
                WriteData(PicProtocal. RS_PacketTx(200, PicProtocal.RSCMD_SYSTEM, 1, 2) );
            }
        }


        /************************************************
       *       按键事件，发出恢复出厂设置指令
       * **********************************************/
        private void btnSysDefault_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定恢复出厂设置?恢复后：\n波特率=115200,\nID=0，\n包容量=512\n", "NOTE", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                WriteData(PicProtocal.RS_PacketTx(200, PicProtocal.RSCMD_SYSTEM, 1, 1));
            }                
        }

        /************************************************
      *       按键事件，清空发送栏
      * **********************************************/
        private void btnClrrchtx_Click(object sender, EventArgs e)
        {
            rchTX.Text = "";
        }


        /************************************************
       *       选择按键事件，曝光选择改变
       * **********************************************/
        private void rdoExpoType_CheckedChanged(object sender, EventArgs e)
        {
            if (rdoAutoExpo.Checked == true)
            {
                comboFixExpo.Enabled = false;                
                lblFixExpo.Enabled = false;
            }
            else
            {
                comboFixExpo.Enabled = true;
                lblFixExpo.Enabled = true;                
            }
        }
        /************************************************
       *       计算一个包在特定波特率下传输所花ms
       * **********************************************/
        public   int CalculatePKTms()
        {
            return (((1000000 / RS_port.BaudRate * 10 * imgobj.stSP.PKTsz / 1000)) * 6);
        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void rbtnTCP_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtnTCP.Checked == true)
            {
                gBoxUart.Enabled = false;
            }
            else {
                gBoxUart.Enabled = true;
            }
        }

        private void Pixcom_Form_FormClosing(object sender, FormClosingEventArgs e)
        {
            //asyncTCP.stop();
        }

        private void btnOpen_Click_1(object sender, EventArgs e)
        {

        }
    }
}
